<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Validator;
use Illuminate\Http\Request;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected $request;

    public function __construct(Request $request) {
        $this->request = $request;
    }

    /**
     * @param $index
     * @param $params
     */
    protected function validateInputParams($index, $params)
    {
        $validator = Validator::make($params, static::VALID_RULES[$index]);
        if ($validator->fails()) {
            throwResponseException(CODE_B_VALID_FAIL, $validator->messages());
        }
    }

    /**
     * @return array
     */
    protected function normalizeSearchOptions()
    {
        $searchOptions = [];

        $searchOptions['keywords'] = $this->request->get('keywords', '');

        return $searchOptions;
    }

    /**
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    protected function normalizeSortOptions($page = 1 , $pageSize = 10)
    {
        $order = $this->request->get('order', 'desc');
        $orderBy = $this->request->get('orderBy', 'created_at');

        $data = [
            'sort_key' => $orderBy,
            'sort' => $order,
            'page' => $this->request->get('page', $page),
            'size' => $this->request->get('limit', $pageSize),
            'all' => $this->request->get('all', 0),
        ];

        if ($data['all'] == 1) {
            unset($data['page']);
        }

        return $data;
    }

    /**
     * 成功响应
     * @param array $arr
     * @param null $msg
     * @return \Illuminate\Http\JsonResponse
     */
    protected function success($arr=[],$msg=null)
    {
        return getSuccessResponse($arr, $msg);
    }

    /**
     * 失败响应
     * @param $code
     * @param null $msg
     * @param null $data
     * @return \Illuminate\Http\JsonResponse
     */
    protected function error($code,$msg=null,$data=null){
        return getErrorResponse($code,$msg,$data);
    }
}
